package controllers;

import java.util.Iterator;
import java.util.List;

import com.google.appengine.repackaged.org.json.JSONArray;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import models.User;
import models.UserLocation;
import models.UserPermission;
import play.data.validation.Required;
import play.mvc.Controller;
import siena.Model;
import static utils.AppConstants.*;

public class Permissions extends Controller {

	/**
	 * @author loai
	 */
	public static void deleteAll() {
		UserPermission.all().delete();
	}

	/**
	 * Do random testing stuff :)
	 * 
	 * @author loai
	 */
	public static void doStuff() {
		render();
		List<User> users = User.all().fetch();
		for (int i = 0; i < users.size(); i++) {
			int j = i == 0 ? 1 : 0;
			UserPermission up = new UserPermission(users.get(j), users.get(i),
					ALWAYS_ASK);
			up.insert();
		}
	}

	/**
	 * show all user permissions
	 * 
	 * @author loai
	 */
	public static void index() {
		List<UserPermission> all = UserPermission.all().fetch();
		String data = "";
		Iterator<UserPermission> iterator = all.listIterator();
		while (iterator.hasNext()) {
			UserPermission up = iterator.next();
			up.receiver.get();
			up.sender.get();
			data += "Sender: " + up.sender + ", Receiver: " + up.receiver
					+ ", Permission: " + up.permission + "\n";
		}
		renderText(data);
	}

	/**
	 * Associate a permission between the users identified by their mobile
	 * phones
	 * 
	 * @author loai
	 */
	public static void setPermission(@Required String receiverMobile,
			@Required String senderMobile, @Required Integer permission) {
		System.out.println("HERER");
		if (validation.hasErrors())
			renderText("Error in HTTP fields");
		User receiver = User.findByPhone(receiverMobile);
		User sender = User.findByPhone(senderMobile);
		// if there no such user(s), abort
		// Temporarily
		if (receiver == null || sender == null)
			renderText("There no such user(s)");
		/*
		 * if there is a userPermission already associated with those two users
		 * then change it, else catch the exception and create a new
		 * userPermission
		 */
		UserPermission userPerm;
		try {
			userPerm = Model.all(UserPermission.class)
					.filter("receiver", receiver).filter("sender", sender)
					.get();
			if (userPerm == null)
				throw new Exception();
			userPerm.setPermission(permission);
			userPerm.update();

		} catch (Exception e) {
			// create new permission
			userPerm = new UserPermission(receiver, sender, permission);
			userPerm.insert();
		}
	}

	/**
	 * Returns a list of userPermission associated with the user identified by
	 * phone, encode it in JSON and send it back. This is to be sent to the
	 * client side
	 * 
	 * @author loai
	 */
	public static void getUsersPermissions(@Required String phone) {
		if (validation.hasErrors()) {
			renderText("Some field(s) are not filled !");
		}
		User user = User.findByPhone(phone);
		if (user == null)
			renderText("No such user !");
		List<UserPermission> usersPermissions = user.getUsersPermissions();
		// List<UserPermission> usersPermissions = UserPermission.all().fetch();
		Iterator<UserPermission> iterator = usersPermissions.listIterator();
		JsonArray jsonArray = new JsonArray();
		while (iterator.hasNext()) {
			UserPermission up = iterator.next();
			up.receiver.get();
			JsonObject jsonObject = new JsonObject();
			jsonObject.addProperty("phone", up.receiver.getPhone());
			jsonObject.addProperty("permission", up.permission);
			jsonObject.addProperty("name", up.receiver.getFirstName() + " "
					+ up.receiver.getLastName());
			jsonArray.add(jsonObject);
		}
		renderText(jsonArray);
	}

	public static void getPermission(@Required String receiverMobile,
			@Required String senderMobile) {
		if (validation.hasErrors())
			renderText("There are errors in the ntype");
		renderJSON(UserPermission.getPermission(receiverMobile, senderMobile));
	}
}
